package service

import (
	"PDF/modules"
	"PDF/utils"
	"fmt"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

func CreateUser(c *gin.Context) {
	user := modules.UserBasic{}
	Name := c.PostForm("name")
	password := c.PostForm("password")
	repassword := c.PostForm("repassword")
	email := c.PostForm("email")

	//检查该用户名是否已注册
	legacy_user, _ := modules.FindUserbyName(Name)
	if legacy_user != nil {
		c.JSON(-1, gin.H{
			"message": "该用户名已注册",
		})
		return
	} else {
		user.Name = Name
		user.Email = email
	}

	//检查密码与重复密码是否相同,相同则为结构体赋值并创建用户
	if password != repassword {
		c.JSON(-1, gin.H{
			"message": "两次密码不一致！",
		})
		return
	}

	//对密码进行加密
	password, err := utils.BcryptEncode(password)
	//加密错误处理
	if err != nil {
		c.JSON(400, gin.H{
			"error": err.Error(),
		})
		return
	}

	user.Password = password
	err = modules.CreateUser(&user)

	//对CreateUser函数中返回的错误进行处理
	if err != nil {
		c.JSON(400, gin.H{
			"error": err.Error(),
		})
	} else {
		c.JSON(200, gin.H{
			"message": "新增用户成功",
		})
	}
}

func Login(c *gin.Context) {
	name := c.PostForm("name")
	password := c.PostForm("password")
	user, err := modules.FindUserbyName(name)
	if err != nil {
		c.JSON(400, gin.H{
			"error": "数据查询失败，错误原因为：" + err.Error(),
		})
		return
	}

	if utils.CheckPasswordHash(password, user.Password) {
		//生成token
		token, err := utils.GenerateToken(user.ID, user.Name, user.Email)
		if err != nil {
			c.JSON(400, gin.H{
				"error": "token生成失败，错误为：" + err.Error(),
			})
			return
		}
		//生成cookies
		cookie := http.Cookie{
			Name:     "S.H.I.T",
			Value:    token,
			Path:     "/",
			HttpOnly: true,      // 这样javascript就无法读取这个cookie
			MaxAge:   3600 * 12, // 设置过期时间, 这里是24小时
			// 如果您的服务运行在HTTPS上，您可能还需要设置Secure属性
			// Secure: true,
		}
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		c.Writer.Header().Set("Access-Control-Allow-Origin", "http://localhost:8080")
		http.SetCookie(c.Writer, &cookie)
		fmt.Println("cookie inited... ...", user.Name, cookie)
		user.LoginTime = time.Now()
		modules.UpdatesUser(uint64(user.ID), user)
		c.JSON(200, gin.H{
			"message": "登录成功！",
			"code":    "0",
			"data":    user,
		})
		return
	}
	c.JSON(-1, gin.H{
		"message": "密码错误",
	})
}
